/*
 * Alloy Analyzer
 * Copyright (c) 2002 Massachusetts Institute of Technology
 *
 * The Alloy Analyzer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The Alloy Analyzer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the Alloy Analyzer; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package alloy.transl;

import java.util.ArrayList;
import java.util.List;

import alloy.ast.ASTDepthFirstVisitor;
import alloy.ast.BinaryFormula;
import alloy.ast.Formula;
import alloy.ast.LogicOp;
import alloy.ast.Node;

/**
 * Gathers formulas disjoined at the root of the given subtree into a flat list.
 * E.g. if the subtree says (A and (B and (C and D))) then this visitor produces
 * the linear list (A and B and C and D).
 */
class GatherDisjoinedFormulasVisitor extends ASTDepthFirstVisitor {
    /**
     * Flat list of disjoined formulas that we find.
     */
    private List /* of Formula */ _disjoinedFormulas = new ArrayList();
    
    //--------//
    // Methods//
    //--------//

    private GatherDisjoinedFormulasVisitor() { }

    /**
     * Starting with a disjunction node, gather a flat list of formulas disjoined there.
     */
    static List /* of Formula */ gatherDisjoinedFormulas(Formula subtree) {
	GatherDisjoinedFormulasVisitor v = new GatherDisjoinedFormulasVisitor();
	subtree.applyVisitor(v);
	return v._disjoinedFormulas;
    }

    public void visit(Node node_) {
	// if it's not one of the specific node types we handle explicitly,
	// then this is a formula from the frontier of a group of disjunctions --
	// record that it is disjoined.
	_disjoinedFormulas.add(node_);
    }

    public void visit(BinaryFormula binaryFormula_) {
	if (binaryFormula_.getOp().equals(LogicOp.OR)) {
	    binaryFormula_.getLeft().applyVisitor(this);
	    binaryFormula_.getRight().applyVisitor(this);
	} else
	    _disjoinedFormulas.add(binaryFormula_);
    }
}
